package com.guomw.report.common.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.SecureRandom;

public class SysUtils {


    private static Log log = LogFactory.getLog(SysUtils.class);

    private static String aecKey = "what123&$@";

    public static String aesEncrypt(String text) throws Exception {

        // 生成key
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128, new SecureRandom(aecKey.getBytes()));
        SecretKey secretKey = keyGenerator.generateKey();
        log.info(secretKey);
        byte[] keybytes = secretKey.getEncoded();
        Key key = new SecretKeySpec(keybytes, "AES");

        // 加密
        // AES/工作模式/填充方式
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] result = cipher.doFinal(text.getBytes("utf-8"));
        return Base64.encodeBase64String(result);
    }

    public static String aesDecrypt(String text) throws Exception {
        // 生成key
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128, new SecureRandom(aecKey.getBytes()));
        SecretKey secretKey = keyGenerator.generateKey();
        log.info(secretKey);
        byte[] keybytes = secretKey.getEncoded();

        // key的转换
        Key key = new SecretKeySpec(keybytes, "AES");


        // 解密
        // AES/工作模式/填充方式
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] result = cipher.doFinal(new Base64().decode(text));
        return new String(result, "utf-8");
    }

}
